using System.Xml;
using Coffee.Utils;

namespace Coffee.SurveyControls
{
    /// <summary>
    /// Summary description for SurveyQuestionsRepeaterTable
    /// </summary>
    public class SurveyQuestionsRepeaterTable : SurveyQuestionsTable
    {
        // REQUIRED: Constructor - just calls the base class that sets up coffee and configuration
        public SurveyQuestionsRepeaterTable(SurveyManager coffee, XmlNode configuration)
            : base(coffee, configuration)
        {

        }

        protected override string GetQuestionHeader()
        {
            return "Section";
        }

        protected override string GetQuestionID(XmlNode question)
        {
            string qid = question.Attributes["id"].Value + counter.ToString();
            counter++;
            return qid;
        }

        int counter = 0;

        protected override XmlNodeList GetQuestions()
        {
            string type = configuration.SelectSingleNode("configuration/question").Attributes["type"].Value;
            string id = configuration.SelectSingleNode("configuration/question").Attributes["id"].Value;

            XmlNodeListMapper data = new XmlNodeListMapper();
            Coffee.Binding.ConfigureBinding(data, configuration.SelectSingleNode("configuration"));
            data.DataBind();

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(data.ToString());

            XmlDocument output = new XmlDocument();
            XmlElement questions = output.CreateElement("questions");
            output.AppendChild(questions);

            XmlNodeList rows = doc.SelectNodes("table/row");

            int ctr = 0;
            foreach (XmlNode row in rows)
            {
                string text = row.SelectSingleNode("text/text()").Value;
                string value = row.SelectSingleNode("value/text()").Value;
                XmlElement question = output.CreateElement("question");
                //question id="IDSName" type="TextBox" questionid="1"
                XmlAttribute attitem = output.CreateAttribute("item");
                attitem.Value = value;
                XmlAttribute attid = output.CreateAttribute("id");
                attid.Value = id;
                XmlAttribute atttype = output.CreateAttribute("type");
                atttype.Value = type;
                XmlElement textNode = output.CreateElement("text");
                textNode.AppendChild(output.CreateTextNode(text));
                question.AppendChild(textNode);
                question.Attributes.Append(attid);
                question.Attributes.Append(attitem);
                question.Attributes.Append(atttype);
                questions.AppendChild(question);
                ctr++;
            }

            return questions.SelectNodes("question");
        }



    }
}